<template>
  <base-breadcrumb title="技术问题清单">
    <searchData :search-data="searchArr" @search="search" />
    <a-card>
      <a-spin :spinning="loading1">
        <a-tabs v-model:activeKey="activeKey" @change="tabTopChange">
          <a-tab-pane :key="item.projectTypeId" :tab="item.projectTypeName" v-for="item in qualityTypes"></a-tab-pane>
        </a-tabs>
      </a-spin>
      <a-row :gutter="10" :style="'height: calc('+GET_REDRESS_PERCENTAGE+'vh - 345px); overflow-y: auto'">
        <a-col :span="4" style="height: 100%">
          <div style="height: 100%; border-right: 1px solid rgba(215, 215, 215, 1); padding-right: 10px; width: 100%; overflow: hidden; box-sizing: border-box">
            <a-spin :spinning="loading2" style="height: 100%">
              <a-input-search style="margin-bottom: 8px" placeholder="搜索" @change="onChange" />
              <a-tree
                :selectedKeys.sync="selectedKeys"
                :expanded-keys="expandedKeys"
                :auto-expand-parent="autoExpandParent"
                :tree-data="gData"
                :replaceFields="{ children: 'children', title: 'name', key: 'id' }"
                @expand="onExpand"
                @select="selectTreeNode"
                style="height: calc(100% - 80px); overflow: auto"
              >
                <template slot="title" slot-scope="{ name, enable }">
                  <span v-if="name.indexOf(searchValue) > -1">
                    {{ name.substr(0, name.indexOf(searchValue)) }}
                    <span style="color: #f50">{{ searchValue }}</span>
                    {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
                  </span>
                  <span v-else>{{ name }}</span>
                  <span style="color: #ff4d4f">{{ !enable ? '（停用）' : '' }}</span>
                </template>
              </a-tree>
              <div style="display: flex; justify-content: space-around">
                <a-button type="primary" @click="openNodeModal(1)" size="small"  v-btnPermission="'tm_057_add_01'">添加</a-button>
                <template v-if="this.gData.length">
                  <a-button :disabled="selectOrg.name == '所有' && !selectOrg.parentId" type="primary" @click="openNodeModal(2)" size="small" v-btnPermission="'tm_057_edi_02'">编辑</a-button>
                  <a-button v-btnPermission="'tm_057_del_03'" v-if="userInfo.currentPost.code === 'CO'" size="small" type="danger" @click="deleteProblemListFn" :disabled="selectOrg.name == '所有'&&!selectOrg.parentId">删除</a-button>
                </template>
              </div>
            </a-spin>
          </div>
        </a-col>
        <a-col :span="20">
          <div class="mb10">
            <a-button v-btnPermission="'tm_057_add_04'" type="primary" @click="handleManage(0)" :disabled="selectOrg.parentId == null || selectOrg.children.length>0">添加问题类型</a-button>
          </div>
          <list-table ref="table" row-key="id" :columns="columns" :request="loadData" :is-init="false" :page-keys="['pageNum', 'pageSize', 'total']">
            <template slot="enable" slot-scope="text">
              {{ text ? '可用' : '不可用' }}
            </template>
            <template slot="action" slot-scope="text, record">
              <MoreButton>
                <a  v-btnPermission="'tm_057_loo_05'" @click="handleManage(2, record)">查看</a>
                <a  v-btnPermission="'tm_057_edi_06'" @click="handleManage(1, record)">编辑</a>
                <a-divider v-btnPermission="record.status == 0 ? 'tm_057_sta_08' : 'tm_057_sto_07'" type="vertical" />
                <a  v-btnPermission="'tm_057_sta_08'" v-if="record.status == 0" @click="handleRemove(record)">启用</a>
                <a v-btnPermission="'tm_057_sto_07'"  v-else @click="handleRemove(record)">停用</a>
              </MoreButton>
            </template>
          </list-table>
        </a-col>
      </a-row>
    </a-card>
    <a-modal v-model="nodeVisible" :title="nodeTitle" @ok="handleOk" okText="提交" width="70%" :confirmLoading="loadingBtn1">
      <a-form-model :model="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="父节点：">
              <a-input disabled v-model="form.parentName" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="子节点：" class="requiredFormItem">
              <a-input v-model="form.name" :maxLength="9" palaceholder="请输入子节点" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
    <!-- 问题分类表单弹窗 -->
    <dialog-problem ref="dialogProblem" :visible.sync="visible" :edit-model="editModel" :form="form" :header-title="headerTitle" @confirm="submitForm" />
  </base-breadcrumb>
</template>

<script>
import { getProjectTypes } from '@/api/project/projects'
import {
  queryTreeListBySearch,
  addProblemListTree,
  editProblemListTree,
  deleteProblemListTree,
  addProblemListTwo,
  getProblemListTwo,
  editProblemListTwo,
  setStatusByPrimaryKeyProblemListTwo
} from '@/api/technical/problemList'
import {mapGetters } from 'vuex'
import dialogProblem from './dialogProblem.vue' // 问题分类表单弹窗
const getParentKey = (key, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some((item) => item.id === key)) {
        parentKey = node.id
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children)
      }
    }
  }
  return parentKey
}
export default {
  name: 'a' + Date.now(),
  components: {
    dialogProblem
  },
  computed: {
    ...mapGetters(['GET_REDRESS_PERCENTAGE']),
    headerTitle() {
      return ['添加问题分类', '编辑问题分类', '查看问题分类'][this.editModel]
    }
  },
  data() {
    return {
      loading1: false,
      loading2: false,
      loadingBtn1: false,
      loadingBtn2: false,
      disabled: false,
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info')),
      desVisible: false,
      desTitle: '添加范围描述',
      row: {
        desc: '',
        status: 1
      }, // 当前列的数据
      nodeVisible: false,
      nodeTitle: '新增节点',
      activeKey: '',
      query: {},
      form: {
        parentName: '',
        name: ''
      },
      rules: {},
      searchArr: [
        {
          name: '问题分类名称',
          value: 'name',
          type: 'input'
        }
      ],
      columns: [
        {
          title: '问题分类名称',
          dataIndex: 'name',
          width: 180
        },
        {
          title: '问题描述',
          ellipsis: true,
          dataIndex: 'description', // 问题描述的字段和规范规定的字段，因为用户录入数据写反了，因此这两个字段反着取
          width: 180
        },
        {
          title: '规范规定',
          ellipsis: true,
          dataIndex: 'standardInfo',
          width: 180
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          width: 180,
          scopedSlots: { customRender: 'action' }
        }
      ],
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      selectedKeys: [],
      selectOrg: {}, //选中节点
      gData: [],
      dataList: [],
      qualityTypes: [],
      nodeId: '', // 节点id
      type: 1, // 1为新增 2为编辑
      listData: [],
      listData2: [],
      visible: false,
      form: {},
      // 操作类型：0 添加 1 编辑 3 查看
      editModel: 0
    }
  },
  mounted() {
    this.getProjectTypes()
  },
  methods: {
    handleDescOk() {},
    editDesc(row, type) {
      this.disabled = type === 'view'
      this.desTitle = type === 'view' ? '查看范围描述' : '编辑范围描述'
      this.row = { ...row, status: row.status ? 1 : 0 }
      this.desVisible = true
    },
    cancel() {
      this.disabled = false
      this.desVisible = false
    },
    projectTypeChange() {
      this.$refs.table.refresh(true)
    },
    // 点击添加节点确定按钮
    handleOk() {
      if (!this.form.name) {
        this.$message.warning('请填写完所有必填项信息')
        return
      }
      let data = {
        programmeTypeId: this.activeKey,
        parentId: this.type === 1 ? this.selectOrg.id : this.selectOrg.parentId,
        name: this.form.name
      }
      this.loadingBtn1 = true
      if (this.type === 1) {
        addProblemListTree(data).then((res) => {
          this.nodeVisible = false
          this.loadingBtn1 = false
          this.form.name = ''
          this.$message.success('添加成功')
          this.getLargeDangerConfigById(this.activeKey)
        })
      } else {
        data.id = this.selectOrg.id
        editProblemListTree(data).then((res) => {
          this.nodeVisible = false
          this.loadingBtn1 = false
          this.form.name = ''
          this.$message.success('修改成功')
          this.getLargeDangerConfigById(this.activeKey)
        })
      }
    },
    //删除树节点
    deleteProblemListFn() {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: `确认删除？`,
        okText: '确认',
        cancelText: '关闭',
        onOk() {
          return deleteProblemListTree({ id: that.selectOrg.id })
            .then((res) => {
              if (res.data.code == '0') {
                that.$message.success('删除成功！')
                that.getLargeDangerConfigById(that.activeKey)
                that.$refs.table.refresh(true)
              }
            })
            .catch((error) => {
              console.log(error)
            })
        }
      })
    },
    // 打开节点弹窗
    openNodeModal(type) {
      this.type = type
      if (type === 1) {
        if (this.listData.length > 0) {
          this.$message.warning('该节点中已存在范围描述，若继续添加子节点，则不能使用该节点中的范围描述')
        }
        this.form.name =null;
        this.form.parentName = this.selectOrg.name
        this.nodeTitle = '新增节点'
      } else {
        this.nodeTitle = '编辑节点'
        this.form.parentName = this.selectOrg.parentName
        this.form.name = this.selectOrg.name
      }
      this.nodeVisible = true
    },
    // 获取树
    getLargeDangerConfigById(id, isInit = false) {
      queryTreeListBySearch({ programmeTypeId: id }).then((res) => {
        this.dataList = []
        this.generateList(res.data)
        this.gData = res.data
        this.loading2 = false
        if (isInit) {
          this.selectedKeys = [this.gData[0].id]
          this.selectOrg = this.gData[0]
          this.form.parentName = this.selectOrg.name || '无'
          this.$nextTick(() => {
            this.$refs.table.refresh(true)
          })
        }
      })
    },
    // 获取工程类别
    getProjectTypes() {
      this.loading1 = true
      this.loading2 = true
      getProjectTypes().then((res) => {
        this.qualityTypes = res.data?.filter((i) => i.status * 1 === 1)
        this.activeKey = this.qualityTypes[0].projectTypeId
        this.loading1 = false
        this.getLargeDangerConfigById(this.activeKey, true)
      })
    },
    //获取列表
    loadData(parameter) {
      const requestParameters = Object.assign({}, parameter, {
        param: {
          menuId: this.selectOrg.id,
          ...this.query
        }
      })
      return getProblemListTwo(requestParameters).then((res) => {
        this.listData = res.data.list
        res.data.totalSize = res.data.total
        return res
      })
    },
    search(val) {
      this.query = val
      this.$refs.table.refresh(true)
    },
    tabTopChange(activeKey) {
      this.getLargeDangerConfigById(activeKey,true)
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onChange(e) {
        const value = e.target.value;
        const expandedKeys = this.dataList
          .map(item => {
            if (item.name.indexOf(value) > -1) {
              console.log(item.name,item.key)
              return getParentKey(item.id, this.gData);
            }
            return null;
          })
          .filter((item, i, self) => item && self.indexOf(item) === i);
        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true,
        });
      },
    selectTreeNode(selectedKeys, { node }) {
      this.selectedKeys = selectedKeys
      this.selectOrg = { ...node.dataRef, parentName: node.$parent?.dataRef?.name || '无' }
      this.$refs.table.refresh(true)
    },
    generateList(data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        node.scopedSlots = { title: 'title' }
        this.dataList.push(node)
        if (node.children && node.children.length > 0) {
          this.generateList(node.children)
        }
      }
    },
    // 提交问题分类表单
    submitForm(e) {
      let that = this
      let api = [addProblemListTwo, editProblemListTwo][that.editModel] // 根据操作切换url地址
      if (that.editModel == 0) {
        e.subItemId = e.id
      }
      api(e)
        .then((res) => {
          that.$refs.dialogProblem.loading = false
          // if (res.data.code === 200 || res.code === 200) {
          that.$message.success(['添加', '编辑'][that.editModel] + '成功！')
          that.visible = false
          that.$refs.table.loadData()
          // } else {
          //   that.$message.warning(['添加', '编辑'][that.editModel] + '失败！')
          // }
        })
        .catch((res) => {
          that.$refs.dialogProblem.loading = false
        })
    },
    // 业务区域：新增/编辑/查看
    handleManage(b, a) {
      // b 操作类型;a 行数据
      this.form = {};
      if (b) {
        this.form = a
      } else {
        this.form.menuId = this.selectOrg.id //菜单iD
        this.form.menuName = this.selectOrg.name //菜单iD
      }
      this.editModel = b
      // 添加
      console.log(this.form,123)
      this.visible = true // 打开弹窗
    },
    // 停启用
    handleRemove(e) {
      let that = this
      let status = ['启用', '停用'][e.status] || '操作'
      that.$confirm({
        title: '温馨提示',
        content: `确认${status}？`,
        okText: '提交',
        cancelText: '关闭',
        onOk() {
          return setStatusByPrimaryKeyProblemListTwo({ id: e.id, status: e.status ? 0 : 1 }).then((res) => {
            // if (res.data.code === 200 || res.code === 200) {
            that.$message.success(status + '成功！')
            that.$refs.table.loadData()
            // } else {
            //   that.$message.warning(status + '失败！')
            // }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
</style>